<template>
  <div class="file-upload-component">
    <div class="section-header" v-if="showHeader">
      <div class="section-title">{{ title }}</div>
      <div class="template-download" v-if="templateUrl || templateName">
        文件模板:
        <span @click="handleDownload" class="link-style">
          {{ templateName || '下载模板' }}
        </span>
      </div>
    </div>
    <div class="section-content">
      <el-upload
        ref="upload"
        action=""
        :http-request="handleUpload"
        :on-change="handleFileChange"
        :before-upload="beforeUpload"
        :limit="1"
        :show-file-list="false"
        drag
        class="upload-area"
      >
        <div class="upload-placeholder">
          <i class="el-icon-upload"></i>
          <div v-if="!uploadedFile" class="upload-text">
            <p>
              将文件拖拽至此区域 <span class="link-text">选择文件导入</span>
            </p>
            <p class="file-type-tip">仅支持: {{ allowedFileTypes.join('、') }}</p>
          </div>
          <div
            v-if="uploadedFile && !isParsing && !parseResult"
            class="file-info"
          >
            <p>{{ uploadedFile.name }}</p>
            <div class="file-actions">
              <el-button size="small" @click.stop="resetUpload">
                重新选择
              </el-button>
              <el-button
                size="small"
                type="primary"
                @click.stop="handleConfirmImport"
              >
                数据解析
              </el-button>
            </div>
          </div>
          <div v-if="isParsing" class="parsing-status">
            <i class="el-icon-loading"></i>
            <span>解析中...({{ progress }}%)</span>
          </div>
          <div
            v-if="!isParsing && parseResult"
            class="parse-result"
            :class="parseResult === '解析成功' ? 'success' : 'error'"
          >
            <i
              :class="
                parseResult === '解析成功'
                  ? 'el-icon-circle-check'
                  : 'el-icon-circle-close'
              "
            ></i>
            <span>{{ parseResult }}</span>
            <el-button
              size="small"
              style="margin-left: 10px"
              @click.stop="resetUpload"
            >
              重新选择
            </el-button>
          </div>
        </div>
      </el-upload>
    </div>
  </div>
</template>

<script>
export default {
  name: 'FileUpload',
  props: {
    // 标题
    title: {
      type: String,
      default: '导入文件'
    },
    // 是否显示头部（标题和模板下载）
    showHeader: {
      type: Boolean,
      default: true
    },
    // 模板下载链接
    templateUrl: {
      type: String,
      default: ''
    },
    // 模板文件名
    templateName: {
      type: String,
      default: ''
    },
    // 允许的文件类型（扩展名，不包含点）
    allowedFileTypes: {
      type: Array,
      default: () => ['xls', 'xlsx']
    },
    // 上传接口函数
    uploadApi: {
      type: Function,
      required: true
    },
    // 成功消息文本
    successMessage: {
      type: String,
      default: '解析成功'
    },
    // 失败消息文本
    errorMessage: {
      type: String,
      default: '解析失败！文件未上传或文件不符合模版要求'
    }
  },
  data() {
    return {
      uploadedFile: null, // 上传的文件
      isParsing: false, // 是否正在解析
      progress: 0, // 解析进度
      parseResult: '' // 解析结果
    }
  },
  methods: {
    // 文件上传前验证
    beforeUpload(file) {
      const fileType = file.name.split('.').pop().toLowerCase()
      if (!this.allowedFileTypes.includes(fileType)) {
        this.$message.error(`仅支持 ${this.allowedFileTypes.join('、')} 文件`)
        return false
      }
      return true
    },
    // 文件选择变化
    handleFileChange(file, fileList) {
      // 调用 beforeUpload 进行文件类型验证
      if (this.beforeUpload(file)) {
        this.uploadedFile = file
        this.parseResult = '' // 重置解析结果
      }
    },
    // 自定义上传处理（不使用，仅用于兼容 el-upload）
    handleUpload(options) {
      // 这里不处理，上传由 handleConfirmImport 函数处理
      console.log('handleUpload', options)
    },
    // 重置上传
    resetUpload() {
      this.$refs.upload.clearFiles()
      this.uploadedFile = null
      this.isParsing = false
      this.progress = 0
      this.parseResult = ''
      this.$emit('reset')
    },
    // 下载模板
    handleDownload() {
      if (this.templateUrl) {
        // 如果提供了模板URL，触发下载事件
        this.$emit('download', this.templateUrl)
      } else {
        this.$message.warning('模板链接未配置')
      }
    },
    // 确认导入（数据解析）
    async handleConfirmImport() {
      if (!this.uploadedFile) {
        this.$message.warning('请先选择文件')
        return
      }

      this.isParsing = true
      this.progress = 0
      this.parseResult = ''

      try {
        if (!this.uploadApi || typeof this.uploadApi !== 'function') {
          console.error('uploadApi 类型:', typeof this.uploadApi, this.uploadApi)
          throw new Error('上传接口函数未正确配置')
        }

        const formData = new FormData()
        formData.append('file', this.uploadedFile.raw)

        console.log('准备调用上传接口，uploadApi:', this.uploadApi)
        console.log('formData:', formData)
        console.log('文件:', this.uploadedFile.raw)

        // 调用传入的上传接口
        const res = await this.uploadApi(formData)

        console.log('上传接口返回:', res)

        if (res && res.code === 200) {
          this.parseResult = this.successMessage
          this.progress = 100

          // 触发成功事件，传递返回的数据
          this.$emit('success', res.data)

          // 处理不同的数据结构
          let listData = null
          if (res.data) {
            // 如果 data 本身就是数组
            if (Array.isArray(res.data)) {
              listData = res.data
            }
            // 如果 data 中有 list 属性
            else if (res.data.list && Array.isArray(res.data.list)) {
              listData = res.data.list
            }
            // 如果 data 中有 entity 属性（可能是单个对象）
            else if (res.data.entity) {
              listData = Array.isArray(res.data.entity) ? res.data.entity : [res.data.entity]
            }
          }

          if (listData && listData.length > 0) {
            this.$emit('parse-success', listData)
          } else {
            // 即使没有 list，也触发 success 事件，让父组件决定如何处理
            this.$emit('parse-success', listData || [])
            this.$message.warning('导入的数据为空')
          }
        } else {
          this.parseResult = this.errorMessage
          const errorMsg = res?.message || res?.errorInfo || '解析失败'
          this.$message.error(errorMsg)
          this.$emit('error', res)
        }
      } catch (error) {
        this.parseResult = this.errorMessage
        console.error('导入文件失败:', error)
        const errorMsg = error?.response?.data?.message || error?.message || '导入失败，请重试'
        this.$message.error(errorMsg)
        this.$emit('error', error)
      } finally {
        this.isParsing = false
        if (this.parseResult !== this.successMessage) {
          this.progress = 0
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.file-upload-component {
  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 0;
    }

    .template-download {
      font-size: 14px;
      color: #606266;

      .link-style {
        color: #3cb7e9;
        text-decoration: underline;
        cursor: pointer;
        margin-left: 5px;

        &:hover {
          color: #551a8b;
        }
      }
    }
  }

  .section-content {
    padding: 0;
  }

  .upload-area {
    width: 100%;

    ::v-deep .el-upload {
      width: 100%;
    }

    ::v-deep .el-upload-dragger {
      width: 100%;
      min-height: 150px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      background-color: #fff;
    }

    .upload-placeholder {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      min-height: 110px;

      .el-icon-upload {
        font-size: 48px;
        color: #c0c4cc;
        margin-bottom: 10px;
      }

      .upload-text {
        text-align: center;

        p {
          margin: 5px 0;
          color: #606266;
          font-size: 14px;

          .link-text {
            color: #0088cf;
            cursor: pointer;
          }

          &.file-type-tip {
            color: #b6b6b6;
            font-size: 12px;
          }
        }
      }

      .file-info {
        text-align: center;

        p {
          margin: 10px 0;
          color: #606266;
          font-size: 14px;
        }
      }

      .parsing-status {
        display: flex;
        align-items: center;
        gap: 10px;
        color: #606266;

        .el-icon-loading {
          font-size: 20px;
          animation: rotating 2s linear infinite;
        }
      }

      .parse-result {
        display: flex;
        align-items: center;
        gap: 10px;
        padding: 10px;

        &.success {
          color: #67c23a;

          .el-icon-circle-check {
            font-size: 20px;
          }
        }

        &.error {
          color: #d54941;

          .el-icon-circle-close {
            font-size: 20px;
          }
        }
      }
    }
  }
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

